package com.huang.CAS;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;

/*
*   CAS compareAndSet 比较并交换
*
* AtomicInteger 解决++原子性问题
* AtomicStampedReference  解决ABA问题
*
* */
public class CsaDemo {
    public static void main(String[] args) {
        // integer 范围-128 127回复用   超过这个数会重新分配内存空间  就不是一个数了
        AtomicStampedReference<Integer> atomicInteger = new AtomicStampedReference<>(1,1); // 带一个乐观锁
       // AtomicInteger atomicInteger = new AtomicInteger(2020);
      //  atomicInteger.compareAndSet(2020,2021);
       // System.out.println(atomicInteger.get());
       // atomicInteger.getAndIncrement();// ++操作
        new Thread(()->{
            int stamp = atomicInteger.getStamp();
            System.out.println("当前版本号是a1----"+stamp);

            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            atomicInteger.compareAndSet(1,2,atomicInteger.getStamp(),atomicInteger.getStamp()+1);
            System.out.println("现在是a2---"+atomicInteger.getStamp());

            atomicInteger.compareAndSet(2,1,atomicInteger.getStamp(),atomicInteger.getStamp()+1);
            System.out.println("现在是a3---"+atomicInteger.getStamp());

        }).start();
        new Thread(()->{
            int stamp = atomicInteger.getStamp();
            System.out.println("当前版本号是b1----"+stamp);

            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            atomicInteger.compareAndSet(1,3,stamp,stamp+1);
            System.out.println("现在是b2---"+atomicInteger.getStamp());
        }).start();

    }
}
